/*
 * miniFreeRTOS SOC System emulation.
 *
 * Copyright (c) 2024- yanl1229@163.com.
 * Written by yanl1229
 *
 * This code is licensed under the GPL.
 */

#include <stdlib.h>
#include "list.h"

void list_init(struct list_head *list)
{
    struct list_node *p = malloc(sizeof(struct list_node));

    p->value = MAX_VALUE;
    p->next = p;
    p->prev = p;
    p->priv = NULL;
    p->list = NULL;

    list->num = 0;
    list->front = p;
}

/**
 * entry插入到链表的尾部
 */
void list_add_tail(struct list_head *list, struct list_node *entry)
{
    struct list_node *front = list->front;
    struct list_node *tail = front->prev;

    tail->next = entry;

    entry->prev = tail;
    entry->next = front;
    front->prev = entry;

    entry->list = list;

    list->num++;
}

/**
 * 将pxNewListItem插入到pxList升序链表
 * value为键值,元素从小到大排列
 */
void list_add_order(struct list_head *list, struct list_node *entry)
{
    struct list_node * p;
    uint32_t value = entry->value;

    /* 插入到链表的尾部 */
    if(value == MAX_VALUE)
    {
        p = list->front->prev;
    }
    else
    {
        /* 从链表的头部开始遍历，找到插入的位置 */
        p = list->front;
        while (p->next->value <= value)
            p = p->next;
    }

    entry->next = p->next;
    entry->next->prev = entry;
    entry->prev = p;
    p->next = entry;

    entry->list = list;

    list->num++;
}

/**
 * 删除pxItemToRemove节点
 */
unsigned long list_remove(struct list_node *entry)
{
    struct list_head *list = entry->list;

    entry->next->prev = entry->prev;
    entry->prev->next = entry->next;

    /* Make sure the index is left pointing to a valid item. */
    if(list->front == entry)
        list->front = entry->prev;

    entry->list = NULL;
    list->num--;

    /* 返回剩余节点数 */
    return list->num;
}
